import DevicePixelRatio from "./utils/devicePixelRatio";
import { Outlet, useNavigate, useLocation } from "react-router-dom";
import { ConfigProvider, message } from "antd";
import zhCN from "antd/locale/zh_CN";
import { useEffect } from "react";
import Cookies from "js-cookie";
const bodyScale = () => {
  const devicewidth = document.documentElement.clientWidth; // 获取当前分辨率下的可视区域宽度
  const scale: number = devicewidth / 1920; // 分母——设计稿的尺寸
  document.body.style.zoom = scale.toString(); // 放大缩小相应倍数
  // 处理缩放导致canvas定位异常
  document.styleSheets[document.styleSheets.length - 1].insertRule(
    "canvas {zoom: " + 1 / scale + "}"
  );
  document.styleSheets[document.styleSheets.length - 1].insertRule(
    "canvas {transform: scale(" + scale + ")}"
  );
  document.styleSheets[document.styleSheets.length - 1].insertRule(
    "canvas {transform-origin: 0 0}"
  );
};
//页面加载时初始化
window.addEventListener("load", () => {
  // 解决电脑分辨率不同导致的页面变形问题
  new DevicePixelRatio().init();
  bodyScale();
});

function App() {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  const location = useLocation();
  const loginOut = () => {
    Cookies.remove("auth_token", { path: "/" });
    Cookies.remove("token_expiry", { path: "/" });
    Cookies.remove("auth_info", { path: "/" });
    navigate("/login");
  };
  // 检查登录是否过期
  const isAuthenticated = (): boolean => {
    const token = Cookies.get("auth_token");
    if (!token) {
      if (location.pathname !== "/login") {
        messageApi.open({
          type: "error",
          content: "请登录",
        });
        navigate("/login");
        return false;
      }
    }

    // 检查 token 是否过期
    const expiryTime = Cookies.get("token_expiry");
    if (expiryTime) {
      const expiryDate = parseInt(expiryTime);
      if (Date.now() > expiryDate) {
        if (location.pathname !== "/login") {
          messageApi.open({
            type: "error",
            content: "登录过期请重新登录",
          });
          loginOut(); // 自动清理过期 token
          return false;
        }
      }
    }

    return true;
  };
  useEffect(() => {
    setInterval(() => {
      console.log("🚀 ~ App1 ~ location:", location);
      isAuthenticated();
    }, 60000); // 每分钟检查一次
  });
  useEffect(() => {
    console.log("🚀 ~ App2 ~ location:", location);
    if (location.pathname !== "/login") {
      isAuthenticated();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location]);
  return (
    <>
      {contextHolder}
      <ConfigProvider locale={zhCN}>
        <Outlet />
      </ConfigProvider>
    </>
  );
}

export default App;
